package com.wintor.server;

import com.google.gdata.client.ClientLoginAccountType;
import com.google.gdata.client.GoogleService;
import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.Service.GDataRequest.RequestType;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ContentType;
import com.google.gdata.util.ServiceException;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class FusionTableWrapper {

	private static final String SERVICE_URL = "http://www.google.com/fusiontables/api/query";
	private GoogleService service;
	private String account;
	private String password;
	private String table_id;

	public FusionTableWrapper(String account, String password, String table_id) {
		service = new GoogleService("fusiontables", "WinterEvolution");
		this.account = account;
		this.password = password;
		this.table_id = table_id;
		try {
			service.setUserCredentials(account, password, ClientLoginAccountType.GOOGLE);
		} catch (AuthenticationException e) {
			System.out.println("Invalid User Credentials: " + e);
		}
	}

	private void runUpdate(String updateQuery){
		try {
			URL url = new URL(SERVICE_URL);
			GDataRequest request = service.getRequestFactory().getRequest(RequestType.INSERT, url, 
					new ContentType("application/x-www-form-urlencoded"));
			OutputStreamWriter writer = new OutputStreamWriter(request.getRequestStream());
			writer.append("sql=" + URLEncoder.encode(updateQuery, "UTF-8"));
			writer.flush();
			request.execute();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}

	public void insertWintor(String evolution_id, String date, String time, String direction, int speed, String unit){
		
		runUpdate("insert into " + table_id + " (Evolution_ID, Date, Time, Direction, Speed, Unit)" +  
				" values ('" + evolution_id + "', '" + date + "', '"+ time + "', '" + direction + "', '" + speed + "', '" + unit + "')");
	}
	
	public static void main(String[] args) {
		 FusionTableWrapper fusionTable =  new FusionTableWrapper("leijiangh@gmail.com", "a3RMd54l", "671581"); 
		 fusionTable.insertWintor("100", "Apr 08, 2011", "11:08:57 AM", "N", 3, "km/h");
	}
}
